package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.*;
import com.lkd.exception.LogicException;
import com.lkd.feign.ChannelService;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskCollectVO;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.service.TaskTypeService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.UserWorkVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }



    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if(vm==null){
            throw new LogicException("该机器不存在");
        }
        //跨服务查询用户微服务，得到用户名
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user==null){
            throw new LogicException("该用户不存在");
        }
        checkCreateTask(vm.getVmStatus(),taskViewModel.getProductType());//验证售货机状态

        if(hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel,taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(  vm.getRegionId() );//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录
        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }

        return true;
    }
    /**
     * 同一台设备下是否存在未完成的工单
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode,int productionType){
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode,innerCode)
                .eq(TaskEntity::getProductTypeId,productionType)
                .le(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }
    /**
     * 创建工单校验
     * @param vmStatus
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(Integer vmStatus,int productType) throws LogicException {
        //如果是投放工单，状态为运营
        if(productType == VMSystem.TASK_TYPE_DEPLOY  && vmStatus == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备已在运营");
        }
        //如果是补货工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_SUPPLY  && vmStatus != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }
        //如果是撤机工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_REVOKE  && vmStatus != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }
    }

    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }

    /**
     * 判断工单状态
     * @param id
     * @return
     */
    @Override
    public boolean accept(Long id) {
        TaskEntity task = this.getById(id);  //查询工单
        if(task.getTaskStatus()!= VMSystem.TASK_STATUS_CREATE ){
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );//修改工单状态为进行
        return this.updateById(task);
    }

    /**
     * 取消工单代码
     * @param id
     * @param cancelVM
     * @return
     */
    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单
        if(task.getTaskStatus()== VMSystem.TASK_STATUS_FINISH  || task.getTaskStatus()== VMSystem.TASK_STATUS_CANCEL ){
            throw new LogicException("工单已经结束");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_CANCEL  );
        task.setDesc(cancelVM.getDesc());
        return this.updateById(task);
    }

    @Autowired
    private MqttProducer mqttProducer;
    @Autowired
    private TaskTypeService taskTypeService;


    @Autowired
    private ChannelService channelService;
    /**
     * 完成工单
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(long id) {
        TaskEntity taskEntity = this.getById(id);
        if(taskEntity.getTaskStatus()== VMSystem.TASK_STATUS_FINISH  || taskEntity.getTaskStatus()== VMSystem.TASK_STATUS_CANCEL ){
            throw new LogicException("工单已经结束");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态为完成
        this.updateById(taskEntity);

        // 根据 productTypeId 查询工单类型
        Integer productTypeId = taskEntity.getProductTypeId();
        LambdaQueryWrapper<TaskTypeEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TaskTypeEntity::getTypeId,productTypeId);
        TaskTypeEntity typeEntity = taskTypeService.getOne(lambdaQueryWrapper);

        //投放工单
        if (typeEntity.getType() == VMSystem.TASK_TYPE_DEPLOY) {
            String topic = "server/vms/completed";
            // 协议类
            TaskCompleteContract msg = new TaskCompleteContract();
            msg.setTaskType(typeEntity.getType());
            msg.setInnerCode(taskEntity.getInnerCode());
            try {
                mqttProducer.send(topic, JsonUtil.serialize(msg));
                System.err.println("发送的消息是：" + JsonUtil.serialize(msg));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            // 补货工单
        }else if ( typeEntity.getType() == VMSystem.TASK_TYPE_SUPPLY){
            String topic = "server/vms/supply";
            // 协议类
            SupplyContract supplyContract = new SupplyContract();
            supplyContract.setInnerCode(taskEntity.getInnerCode());

            List<SupplyChannel> supplyData = new ArrayList<>();
            // 根据工单id 查询补货工单详情
            Long taskId = taskEntity.getTaskId();
            List<TaskDetailsEntity> detailsEntityList = taskDetailsService.getByTaskId(taskId);
            for (TaskDetailsEntity taskDetailsEntity : detailsEntityList) {
                SupplyChannel supplyChannel = new SupplyChannel();
                supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());
                // 远程调用  根据机器编号和货到编号查询机器
                ChannelEntity channelInfo = channelService.getChannelInfo(taskEntity.getInnerCode(), taskDetailsEntity.getChannelCode());
                supplyChannel.setChannelId(channelInfo.getChannelId().toString());
                supplyChannel.setSkuId(taskDetailsEntity.getSkuId());
                supplyChannel.setSkuName(taskDetailsEntity.getSkuName());
                supplyChannel.setSkuImage(taskDetailsEntity.getSkuImage());
                supplyData.add(supplyChannel);
            }
            supplyContract.setSupplyData(supplyData);
            try {
                mqttProducer.send(topic,JsonUtil.serialize(supplyContract));
                System.err.println("发送的消息是：" + JsonUtil.serialize(supplyContract));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 获取当时工单汇总信息
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TaskReportInfoVO> getTaskReportInfo(LocalDateTime start, LocalDateTime end) {
        //运营工单总数total
        var supplyTotal = this.taskCount( start,end,false, null );
        //运维工单总数
        var repairTotal = this.taskCount( start,end,true, null );
        //完成的运营工单总数
        var completedSupply = this.taskCount( start,end,false, VMSystem.TASK_STATUS_FINISH );
        //完成的运维工单总数
        var completedRepair = this.taskCount( start,end,true, VMSystem.TASK_STATUS_FINISH );
        //拒绝掉的运营工单总数
        var cancelSupply = this.taskCount( start,end,false, VMSystem.TASK_STATUS_CANCEL );
        //拒绝掉的运维工单总数
        var cancelRepair = this.taskCount( start,end,true, VMSystem.TASK_STATUS_CANCEL );
        // 获取运营人员数量
        var operatorCount = userService.getOperatorCount();
        //获取运维人员总数
        var repairerCount = userService.getRepairerCount();

        List<TaskReportInfoVO> result = Lists.newArrayList();

        //运营人员
        var supplyTaskInfo = new TaskReportInfoVO();
        supplyTaskInfo.setTotal(supplyTotal);
        supplyTaskInfo.setCancelTotal(cancelSupply);
        supplyTaskInfo.setCompletedTotal(completedSupply);
        supplyTaskInfo.setRepair(false);
        supplyTaskInfo.setWorkerCount(operatorCount);
        result.add(supplyTaskInfo);

        //运维人员
        var repairTaskInfo = new TaskReportInfoVO();
        repairTaskInfo.setTotal(repairTotal);
        repairTaskInfo.setCancelTotal(cancelRepair);
        repairTaskInfo.setCompletedTotal(completedRepair);
        repairTaskInfo.setRepair(true);
        repairTaskInfo.setWorkerCount(repairerCount);
        result.add(repairTaskInfo);
        return result;
    }

    /**
     *获取人员排名
     * @param start
     * @param end
     * @param isRepair
     * @param regionId
     * @return
     */
    @Override
    public List<UserWorkVO> getUserWorkTop10(LocalDate start, LocalDate end, Boolean isRepair,Long regionId) {
        var qw = new QueryWrapper<TaskEntity>();
        qw
                .select("count(user_id) as user_id,user_name")
                .lambda()
                .ge(TaskEntity::getUpdateTime,start)
                .lt(TaskEntity::getUpdateTime,end.plusDays(1))
                .eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_FINISH)
                .groupBy(TaskEntity::getUserName)
                .orderByDesc(TaskEntity::getUserId)
                .last("limit 10");
        if(regionId >0){
            qw.lambda().eq(TaskEntity::getRegionId,regionId);
        }
        if(isRepair){
            qw.lambda().ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else {
            qw.lambda().eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }
        var result = this
                .list(qw)
                .stream()
                .map(t->{
                    var userWork = new UserWorkVO();
                    userWork.setUserName(t.getUserName());
                    userWork.setWorkCount(t.getUserId());
                    return userWork;
                }).collect(Collectors.toList());
        return result;
    }

    /**
     * 获取工单报表
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TaskCollectVO> getTaskReport(String start, String end) {

        List<TaskCollectVO> vos = new ArrayList<>();
        //从开始日期到截至日期，逐条统计
        try {
            List<String> dates = findDates(start, end);
            for (String date : dates) {
                TaskCollectVO vo = new TaskCollectVO();
                vo.setCollectDate(LocalDate.parse(date));
                vo.setFinishCount(getCount(LocalDate.parse(date),VMSystem.TASK_STATUS_FINISH));
                vo.setProgressCount(getCount(LocalDate.parse(date),VMSystem.TASK_STATUS_PROGRESS));
                vo.setCancelCount(getCount(LocalDate.parse(date),VMSystem.TASK_STATUS_CANCEL));
                vos.add(vo);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  vos;
    }

    /**
     * 获取用户工作量详情
     * @param userId
     * @param start
     * @param end
     * @return
     */
    @Override
    public UserWorkVO getUserWork(Integer userId, LocalDateTime start, LocalDateTime end) {
        var userWork = new UserWorkVO();
        userWork.setUserId(userId);
        //并行处理提高程序吞吐量
        //获取用户完成工单数
        var workCount = this.getCountByUserId(userId,VMSystem.TASK_STATUS_FINISH,start.toLocalDate(),end);
        userWork.setWorkCount(workCount);
        //获取工单总数
        var total = this.getCountByUserId(userId,null,start.toLocalDate(),end);
        userWork.setTotal(total);
        //获取用户拒绝工单数
        var cancelCount = this.getCountByUserId(userId,VMSystem.TASK_STATUS_CANCEL,start.toLocalDate(),end);
        userWork.setCancelCount(cancelCount);
        //获取进行中得工单数
        var progressTotal = this.getCountByUserId(userId,VMSystem.TASK_STATUS_PROGRESS,start.toLocalDate(),end);
        userWork.setProgressTotal(progressTotal);
        return userWork;
    }


    //根据工单状态，获取用户(当月)工单数
    private Integer getCountByUserId(Integer userId,Integer taskStatus,LocalDate start,LocalDateTime end){
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw
                .ge(TaskEntity::getUpdateTime,start)
                .le(TaskEntity::getUpdateTime,end);
        if(taskStatus != null ){
            qw.eq(TaskEntity::getTaskStatus,taskStatus);
        }
        if(userId != null) {
            qw.eq(TaskEntity::getUserId,userId);
        }
        return this.count(qw);
    }

    /**
     * 获取不同状态的工单数量
     * @param start
     * @param taskStatus
     * @return
     */
    private int getCount(LocalDate start,Integer taskStatus) {
        LambdaQueryWrapper<TaskEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(TaskEntity::getUpdateTime,start)
                          .le(TaskEntity::getUpdateTime,start.plusDays(1))
                          .eq(TaskEntity::getTaskStatus,taskStatus);
        int count = this.count(lambdaQueryWrapper);
        return count;
    }


    /**
     * *************看我看我**************
     * 传入两个时间范围，返回这两个时间范围内的所有时间，并保存在一个集合中
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> findDates(String beginTime, String endTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }



    /**
     * 统计工单数量
     * @param start
     * @param end
     * @param repair 是否是运维工单
     * @param taskStatus
     * @return
     */
    private int taskCount(LocalDateTime start, LocalDateTime end , Boolean repair , Integer taskStatus ){
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        qw.ge(TaskEntity::getUpdateTime,start)
                .le(TaskEntity::getUpdateTime,end);
        //按工单状态查询
        if(taskStatus!=null){
            qw.eq(TaskEntity::getTaskStatus,taskStatus);
        }
        if(repair){//如果是运维工单
            qw.ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else{
            qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }
        return this.count(qw);
    }
}
